﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Gollie.Mime;
using Gollie.WebCache;
using NLog;

namespace Gollie
{
    public class BaseForm : Page
    {
		protected static Logger logger = LogManager.GetCurrentClassLogger();

        protected override PageStatePersister PageStatePersister
        {
            get
            {
                return new SessionPageStatePersister(this);
            }
        }

		//protected void ResponseAsImage(string path)
		//{
		//	try
		//	{
		//		if (string.IsNullOrEmpty(path))
		//			return;

		//		byte[] allBytes = File.ReadAllBytes(path);
		//		Response.ContentType = Gollie.Mime.MimeMapping.GetMimeMapping(Path.GetExtension(path));
		//		//Response.AddHeader("content-disposition", "attachment; filename=\"" + path + "\"");
		//		Response.OutputStream.Write(allBytes, 0, allBytes.Length);
		//		Response.OutputStream.Flush();
		//		Response.End();
		//	}
		//	catch (System.Threading.ThreadAbortException)
		//	{
		//	}
		//	catch
		//	{
		//		Response.End();
		//	}
		//}

        protected override void OnLoad(EventArgs e)
        {
			bool hideAll = (ConfigAppSettings.GetValue("hideallpages") != null && ConfigAppSettings.GetValue("hideallpages") != "0");
			if (hideAll && Session["userinfo"] == null && Session["nothidden"] == null)
			{
				Server.Transfer("/ComingSoon.aspx");
			}

			this.LogVisit();

            //no page is cached on the client!
            Response.Cache.SetNoStore();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

			//back-button refreshes the page
			Response.Cache.SetAllowResponseInBrowserHistory(false);
            
            base.OnLoad(e);
        }

		protected virtual void LogVisit()
		{
			if (!this.IsPostBack)
			{
				if (Gollie.NlogExtension.Extensions.IsBot(Request.UserAgent) == false)
					logger.Info("User Agent: {0}", Request.UserAgent);

				logger.Info("Visited: {0}", this.Page.Request.RawUrl);
			}
		}

        protected UserInfo UserInfo
        {
           get { return (UserInfo)Session["userinfo"]; }
        }

    }
}